<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class order extends core {
	private $order_mod;
	private $commission_mod;

	public function __construct() {
		parent::__construct();
		$this->order_mod = m("order");
		$this->commission_mod = m("commission");
		header("Content-type:text/html;charset=utf-8");
	}

	//订单列表
	public function index() {
		
		// $total_price = $paid_price = $yue_paid_price = $completed_price = 0;
		$where = '';
		$status = (isset($_GET['status'])) ? trim($_GET['status']) : '';
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
		$order_id = (isset($_GET['order_id'])) ? trim($_GET['order_id']) : '';
		$shop_id = (isset($_GET['shop_id'])) ? intval($_GET['shop_id']) : 0;
		$pay_method = (isset($_GET['pay_method'])) ? trim($_GET['pay_method']) : '';
		$integral_order = (isset($_GET['integral_order'])) ? intval($_GET['integral_order']) : 1;

		if ($keyword) {
			$where .= " AND (order_sn LIKE '%{$keyword}%' OR o.name LIKE '%{$keyword}%' OR o.mobile LIKE '%{$keyword}%'  
				OR o.address LIKE '%{$keyword}%' )";
		}
		if (strlen($status)) {
			$where .= " AND o.status IN ({$status})";
		}
		if (strlen($order_id)) {
			$where .= " AND o.id='{$order_id}'";
		}
		if ($shop_id) {
			$where .= " AND o.shop_id='{$shop_id}'";
		}
		if (strlen($pay_method)) {
			$where .= " AND o.pay_method='{$pay_method}'";
		}
		$where .= " AND o.integral_order='{$integral_order}'";
		//分页
		$this->setpages(array('order_id'=>$order_id, 'keyword'=>$keyword, 'status'=>$status, 
			 'shop_id'=>$shop_id, 'pay_method'=>$pay_method, 'integral_order'=>$integral_order 
			));
		$sql = "SELECT o.* , s.name as shop_name ,m.name as 
			member_name FROM jf_order o LEFT JOIN jf_shop s ON o.shop_id=s.id  
			LEFT JOIN jf_member m ON o.member_id = m.id
			WHERE 1 {$where} ORDER BY o.id DESC";
		// echo $sql;,g.goods_name,g.quantity,g.price ,g.goods_pic
		$rs = $this->ezr->get_results($sql);
		$nav = $this->ezr->get_navigation();
		if ($rs) {
			foreach ($rs as $key => $val) {
				$sql = "SELECT goods_name , quantity ,price ,goods_pic FROM jf_order_goods  
						WHERE order_id = '$val[id]'";
				$order_goods = $this->db->get_results($sql);
				$rs[$key]['goods'] = $order_goods;
			}
		}
		$this->smarty->assign('rs',$rs);
		$sql = "SELECT id,name FROM jf_shop ORDER BY  id ASC";
		$shops = $this->db->get_results($sql);
		$this->smarty->assign('shops',$shops);
		//
		$this->smarty->assign('status',$status);
		$this->smarty->assign('keyword',$keyword);
		$this->smarty->assign('shop_id',$shop_id);
		$this->smarty->assign('order_id',$order_id);
		$this->smarty->assign('pay_method',$pay_method);
		$this->smarty->assign('integral_order',$integral_order);
		$this->smarty->assign('page',$nav);
		$this->smarty->assign('where',$where);
		$this->display();
	}

	//获取查询条件下的订单金额
	private function _get_total_price($order_status, $where) {
		$sql = "SELECT sum(total_price)  
			FROM jf_order o LEFT JOIN im_beautician b ON o.beautician_id=b.id 
			LEFT JOIN jf_beautyshop s ON o.shop_id=s.id 
			LEFT JOIN jf_member_cash_coupon mcc ON o.member_cash_coupon_id=mcc.id 
			WHERE o.status IN ({$order_status}) AND o.pay_method<>'yue' {$where}";
		$price = floatval($this->db->get_var($sql));
		$price = number_format($price, 2);
		return $price;
	}

	//余额支付
	private function _get_yue_pay_total_price($order_status, $where) {
		$sql = "SELECT sum(total_price)  
			FROM jf_order o LEFT JOIN im_beautician b ON o.beautician_id=b.id 
			LEFT JOIN jf_beautyshop s ON o.shop_id=s.id 
			LEFT JOIN jf_member_cash_coupon mcc ON o.member_cash_coupon_id=mcc.id 
			WHERE o.status IN ({$order_status}) AND o.pay_method='yue' {$where}";
		$price = floatval($this->db->get_var($sql));
		$price = number_format($price, 2);
		return $price;
	}

	//详情
	public function edit() {
		if (IS_POST) {
			$this->save();
		} else {
			$order_id = (isset($_GET['order_id']) && intval($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
			$sql = "SELECT o.*,m.name as member_name ,m.id as member_id   
				FROM jf_order o   LEFT JOIN jf_member m ON o.member_id = m.id
				WHERE o.id='{$order_id}'";
			// echo $sql;
			$order = $this->db->get_row($sql);
			if (!$order) $this->error('记录不存在');
			// $order->status_name = $this->order_mod->status_name($order->status);
			$sql = "SELECT og.* ,s.name as shop_name FROM jf_order_goods og 
					LEFT JOIN jf_shop s ON og.shop_id=s.id WHERE og.order_id = {$order_id}";
			$goods = $this->db->get_results($sql);
			$this->smarty->assign('row',$order);
			$this->smarty->assign('goods',$goods);
			$this->display();
		}
	}

	//保存
	public function save() {
		$update_sql = '';
		$shipping_time = "";
		$shouhuo_time = "";
		$id = (isset($_POST['id']) && intval($_POST['id'])) ? intval($_POST['id']) : 0;
		$total_price = (isset($_POST['total_price']) && floatval($_POST['total_price'])) ? floatval($_POST['total_price']) : 0;
		$address = (isset($_POST['address']) && trim($_POST['address'])) ? trim($_POST['address']) : '';
		$shipping_company = (isset($_POST['shipping_company']) && trim($_POST['shipping_company'])) ? trim($_POST['shipping_company']) : '';
		$shipping_number = (isset($_POST['shipping_number']) && trim($_POST['shipping_number'])) ? trim($_POST['shipping_number']) : '';
		$shipping_price = (isset($_POST['shipping_price']) && trim($_POST['shipping_price'])) ? trim($_POST['shipping_price']) : '';
		$print = (isset($_POST['print']) && trim($_POST['print'])) ? intval($_POST['print']) : 0;
		$status = isset($_POST['status']) ? intval($_POST['status']) : -1;
		$oldstatus = isset($_POST['oldstatus']) ? intval($_POST['oldstatus']) : -1;
		$see = isset($_POST['see']) ? intval($_POST['see']) : 0;
		$price = (isset($_POST['price']) && intval($_POST['price'])) ? $_POST['price'] : '' ;
		$goods_id = (isset($_POST['goods']) && intval($_POST['goods'])) ? $_POST['goods'] : '' ;
		//更改是否阅读
		if($status >= 0 && $status < 4 && $status !== $oldstatus){
			$see = 1;
		}
		//发货时间
		if($status == 2){
			$shipping_time = " , shipping_time = '".time()."'";
		}
		if($status == 3){
			$shouhuo_time = " , shouhuo_time = '".time()."'";
		}
		//更新订单信息
		$sql = "UPDATE jf_order SET address='{$address}',total_price='{$total_price}',  status='{$status}', 
				 shipping_company='{$shipping_company}', shipping_number='{$shipping_number}' , 
				 shipping_price='{$shipping_price}' ,see='{$see}'  {$shipping_time}  {$shouhuo_time} 
				WHERE id='{$id}'";
				// var_dump($sql);exit;
		$this->db->query($sql);
		if($price){
			foreach ($price as $key => $va) {
				foreach ($goods_id as $k => $val) {
					if($key == $k){
						$sql = "UPDATE jf_order_goods SET price='{$va}' WHERE order_id='{$id}' AND id ='{$val}'";
						$this->db->query($sql);
					}
				}
			}
		}
		//订单佣金转账到会员的佣金
		// print_r($status);exit;
		if($status >= 3 && $id > 0){
			// print_r($status);exit;
			$this->commission_mod->turn_commission($id);
		}
		//退回佣金
		if($status < 0){
			$this->commission_mod->cancel($id);
		}
		if($print > 0){
			header("Location:?app=order&act=print_order&order_id={$id}");
		}else{
			header("Location:?app=order&act=index");
		}
		
	}

	//删除
	public function delete() {
		$order_id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		$sql = "DELETE FROM jf_order WHERE id='{$order_id}'";
		$this->db->query($sql);
		header("Location:?app=order&act=index");
	}	
	//发货单
	public function print_order(){
		$id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		$sql = "SELECT o.*,m.name as member_name FROM jf_order o LEFT JOIN jf_member m ON o.member_id = m.id 
			WHERE o.id = {$id} ORDER BY o.id DESC";
		$row = $this->db->get_row($sql);
		$sql ="SELECT g.*,s.name as shop_name FROM jf_order_goods g LEFT JOIN jf_shop s ON g.shop_id =s.id 
			WHERE g.order_id = {$id}";
		$goods = $this->db->get_results($sql);
		$total = 0;
		$i = 0;
		foreach ($goods as  $value) {
			$i =$value->sort= $i + 1;
			$total = $value->quantity +$total;
		}
		$this->smarty->assign('total',$total);
		$this->smarty->assign('goods',$goods);
		$this->smarty->assign('row',$row);
		$this->display();
	}

	//导出
	public function export() {
		$fields = array(
			'id'=>'ID',
			'order_sn'=>'订单号',
			'member_name'=>'下单人',
			// 'goods_pic'=>'图片',
			'goods_name'=>'商品',
			'cost_price'=>'成本价',
			'total_price'=>'兑换积分',
			'category_name'=>'商品分类',
			'name'=>'收货人',
			'mobile'=>'电话',
			'province'=>'省',
			'city'=>'市',
			'district'=>'区',
			'address'=>'地址',
			'add_time'=>'下单时间',
			'pay_time'=>'支付时间',
			'total_price'=>'订单总价',
			'pay_method'=>'支付方式',
			'status_name'=>'订单状态'
			//'meals'=>'套餐',
		);
		$where = (isset($_GET['where']) && trim($_GET['where'])) ? trim($_GET['where']) : '';
		$where = stripcslashes($where);
		$sql = "SELECT o.* ,g.goods_name,g.quantity,g.price ,g.goods_pic,m.name as 
			member_name ,gs.cost_price ,c.name as category_name FROM jf_order o LEFT JOIN jf_order_goods g ON o.id = g.order_id 
			LEFT JOIN jf_goods gs ON g.goods_id = gs.id 
			LEFT JOIN jf_goods_category c ON gs.category_id = c.id 
			LEFT JOIN jf_member m ON o.member_id = m.id 
			WHERE 1 {$where} ORDER BY o.id DESC";
		//echo $sql;
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $key => $row) {
				$rs[$key]->status_name = $this->order_mod->status_name($row->status);
				if ($row->add_time) $rs[$key]->add_time = date("Y-m-d H:i:s", $row->add_time);
				if ($row->pay_time) $rs[$key]->pay_time = date("Y-m-d H:i:s", $row->pay_time);
			}
			export_excel($rs, $fields, "order");
		}
	}
	public function return_goods(){
		$where = '';
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : '';
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
		if ($keyword) {
			$where .= "AND (m.name LIKE '%{$keyword}%')";
		}
		if ($id) {
			$where .= "AND r.id='{$id}'";
		}
		//分页
		$this->setpages(array('id'=>$id, 'keyword'=>$keyword));

		$sql = "SELECT r.*, m.name FROM jf_order_refund r LEFT JOIN jf_member m ON r.member_id=m.id 
			WHERE 1 {$where} ORDER BY r.id DESC, r.status ASC";
		$rs = $this->ezr->get_results($sql);
		$nav = $this->ezr->get_navigation();
		$this->smarty->assign('rs',$rs);
		$this->smarty->assign('page',$nav);
		$this->display();
	}
	public function return_edit(){
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "SELECT r.*, m.name FROM jf_order_refund r LEFT JOIN jf_member m ON r.member_id=m.id 
			WHERE r.id={$id}";
		$row = $this->db->get_row($sql);
		$this->smarty->assign('row',$row);
		$this->display();
	}
	//删除
	public function return_goods_delete() {
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$order_id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		$sql = "DELETE FROM jf_order_refund WHERE id='{$id}' OR order_id='{$order_id}'";
		$this->db->query($sql);
		header("Location:?app=order&act=return_goods");
	}

	//第三方退款
	private function _refund($order_id, $order_sn, $trade_no, $total_price, $pay_method, $out_refund_no, $refund_id, $member_id=0, $mobile='') {
		if ($pay_method=='wxpay' || $pay_method=='wxpay_h5') {
			if ($pay_method=='wxpay') {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundAppHelper/WxPay.Api.php");
			} else {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundWxHelper/WxPay.Api.php");
			}
			$input = new WxPayRefund();
			if ($trade_no!='') {
				$input->SetTransaction_id($trade_no); //微信订单号
			} else {
				$input->SetOut_trade_no($order_sn); //原订单号
			}
			$input->SetTotal_fee($total_price*100); //订单金额，单位分
			$input->SetRefund_fee($total_price*100); //退款金额
			$input->SetOp_user_id(WxPayConfig::MCHID); //操作员账号，一般为商户号
			$input->SetOut_refund_no($out_refund_no); //退款订单号
			$data = WxPayApi::refund($input);
			//foreach ($data as $k=>$v) echo "<font color='#f00;'>$k</font> : $v<br/>";exit;
			if ($data["return_code"]=='SUCCESS') {
				if ($data["result_code"]=='SUCCESS') {
					$sql = "UPDATE jf_order_refund SET status='1' WHERE id='{$refund_id}'";
					$this->db->query($sql);
					$sql = "UPDATE jf_order SET status='-2' WHERE id='{$order_id}'";
					$this->db->query($sql);
				} else {
					error($data["err_code_des"]);
				}
			} else {
				error($data["return_msg"]);
			}
		} else if ($pay_method=='alipay') {
			require_once(FRAMEWORK_PATH . "/class/alipay/alipay.config.php");
			require_once(FRAMEWORK_PATH . "/class/alipay/lib/alipay_refund_nopwd_service.php");
			$seller_email = $alipay_config['seller_email']; //卖家支付宝帐户
			$refund_date = date('Y-m-d H:i:s'); //退款当天日期
			$batch_no = date('YmdHis'); //批次号, 格式：当天日期[8位]+序列号[3至24位]，如：201008010000001
			$batch_num = 1; //退款笔数
			//必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
			$detail_data = "{$trade_no}^{$total_price}^买家主动退款"; //退款详细数据
			//必填，具体格式请参见接口技术文档，单笔退款数据集格式：原付款支付宝交易号^退款总金额^退款理由
			$notify_url = "http://".$_SERVER['SERVER_NAME']."/notify_url_refund.php"; //异步通知页面
			//构造要请求的参数数组，无需改动
			$parameter = array(
				//接口名称，不需要修改
				"service"			=> "refund_fastpay_by_platform_nopwd",
				//获取配置文件(alipay_config.php)中的值
				"partner"			=> trim($alipay_config['partner']),
				"notify_url"		=> $notify_url,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
				//必填参数
				"refund_date"		=> $refund_date,
				"batch_no"			=> $batch_no,
				"batch_num"			=> $batch_num,
				"detail_data"		=> $detail_data
			);
			//构造请求函数, 配置环境须支持SSL
			$alipay = new alipay_refund_nopwd_service($parameter, $alipay_config['key'], $alipay_config['sign_type_refund']);
			$url = $alipay->create_url();
			$data = file_get_contents($url);
			$nodeIs_success = '';
			$nodeError_code = '';
			$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
			$obj = (array)$obj;
			//writeLog(json_encode($obj));
			if (isset($obj['is_success'])) $nodeIs_success = $obj['is_success']; //获取成功标识is_success
			if (isset($obj['error'])) $nodeError_code = $obj['error']; //获取错误代码 error
			if ($nodeIs_success=="T") {
				$sql = "UPDATE jf_order_refund SET status='1' WHERE id='{$refund_id}'";
				$this->db->query($sql);
				$sql = "UPDATE jf_order SET status='-2' WHERE id='{$order_id}'";
				$this->db->query($sql);
			} else {
				error($nodeError_code);
			}
		} else if ($pay_method=='yue') {
			$sql = "UPDATE member SET money=money+{$total_price} WHERE member_id='{$member_id}'";
			$this->db->query($sql);
			$sql = "UPDATE jf_order_refund SET status='1' WHERE id='{$refund_id}'";
			$this->db->query($sql);
			$sql = "UPDATE jf_order SET status='-2' WHERE id='{$order_id}'";
			$this->db->query($sql);
		}
	}
	//退货退款审核，1:退款, 2:退货
	public function order_check_return_goods($order_id=0, $reason='', $status=1) {
		if (!$order_id) {
			$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
			$reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
			$status = (isset($_POST['status']) && trim($_POST['status'])) ? intval($_POST['status']) : 0;
		}
		if ($order_id) {
			//判断是退款还是退货
			$sql = "SELECT type FROM jf_order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
			$type = $this->db->get_var($sql);
			
			$sql = "SELECT * FROM jf_order WHERE id='{$order_id}'";
			$order = $this->db->get_row($sql);

			if ($status==1) {
				$sql = "SELECT id, out_refund_no FROM jf_order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
				$refund = $this->db->get_row($sql);
				$this->_refund($order_id, $order->parent_order_sn, $order->trade_no, $order->total_price, $order->pay_method, $refund->out_refund_no, $refund->id, $order->member_id, $order->mobile);
				if ($type==1) {
					$reason = "已退款";
				} else {
					$sql = "UPDATE jf_order SET status='-3' WHERE id='{$order_id}'";
					$this->db->query($sql);
					$sql = "SELECT shop_id FROM jf_order WHERE id='{$order_id}'";
					$shop_id = $this->db->get_var($sql);
					$sql = "SELECT return_province, return_city, return_district, return_address, return_name, return_mobile FROM jf_shop WHERE id='{$shop_id}'";
					$row = $this->db->get_row($sql);
					$reason = "退货地址：{$row->return_province}{$row->return_city}{$row->return_district}{$row->return_address}，联系人：{$row->return_name}，电话：{$row->return_mobile}";
				}
				//扣减退货退款后会员的佣金
				$this->_reduce_order_commission($order_id);
			}
			$sql = "UPDATE jf_order_refund SET status='{$status}', audit_time='".time()."', audit_memo='{$reason}' WHERE order_id='{$order_id}'";
			$this->db->query($sql);

			//发送短信、推送
			$member_id = -1;
			$notify = '';
			$sms = array();
			$template_id = 0;
			if ($status==1) {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退款成功，退款金额为{$order->total_price}元";
					$sms = array($order->order_sn, "{$order->total_price}元");
					$template_id = 83095;
				} else {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退货成功";
					$sms = array($order->order_sn);
					$template_id = 83101;
				}
			} else {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您申请的退款请求失败，请联系卖家";
					$template_id = 83103;
				} else {
					$member_id = $order->member_id;
					$notify = "您申请的退货请求失败，请联系卖家";
					$template_id = 83102;
				}
			}
			$this->send_notify_sms($notify, $member_id, true, $sms, $template_id);
			
			if ($status==1 && $type==1) {
				switch ($order->pay_method) {
					case 'wxpay':
					case 'wxpay_h5':
					case 'alipay':
						header('Location:index.php?app=order&act=return_goods');
						break;
					case 'yue':
						if ($order->member_id == $this->member_id) {
							header('Location:index.php?app=order&act=return_goods');
							// success('订单已退款，请在会员中心查看您的余额是否已到账');
						}
						break;
				}
			}
		}
		header('Location:index.php?app=order&act=return_goods');
	}

	//退货退款成功后，扣减会员的佣金
	private function _reduce_order_commission($order_id) {
		$sql = "SELECT * FROM jf_member_commission WHERE parent_id='{$order_id}' AND status=1 AND commission_type = 1";
		$commissions = $this->db->get_results($sql);
		if ($commissions) {
			foreach ($commissions as $k => $commission) {
				$money = $commission->commission;
				if ($money) {
					$sql = "SELECT commission FROM jf_member WHERE id='{$commission->member_id}'";
					$member = $this->db->get_row($sql);
					if ($member) {
						if ($member->commission>=$money) {
							$member->commission = $member->commission - $money;
						} else {
							$member->commission = 0;
						}
						$sql = "UPDATE jf_member SET commission='{$member->commission}' WHERE id='{$commission->member_id}'";
						$this->db->query($sql);
					}
				}
			}
		}
		$sql = "UPDATE jf_member_commission SET status='-1' WHERE parent_id='{$order_id}' AND commission_type = 1";
		$this->db->query($sql);
	}

}
